/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen.view;

import almacen.bean.Producto;
import almacen.bean.Proveedor;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


/**
 *
 * @author Antonio
 */
public class formProducto extends javax.swing.JFrame {
    
    SessionFactory fabrica = new Configuration().configure().buildSessionFactory();
    Producto producto = new Producto();
    List<Producto> lista_producto = new ArrayList();
    int posicion_actual = 0;
    int tamano_lista = 0;
    String lista = "from Producto";
    String orden = " order by descripcion";
    boolean primeraVezProveedor=true;
    /**
     * Creates new form formProducto
     */
    public formProducto() {
        initComponents();
        rellenar_jtable();
        jTable1.setSelectionBackground(Color.yellow);
        rellenaJComboBox();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grupo_orden = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tf_codigo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        tf_descripcion = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        tf_tipo = new javax.swing.JTextField();
        tf_proveedor = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        tf_obs = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        bt_nuevo = new javax.swing.JButton();
        bt_guardar = new javax.swing.JButton();
        bt_borrar = new javax.swing.JButton();
        bt_primero = new javax.swing.JButton();
        bt_anterior = new javax.swing.JButton();
        bt_siguiente = new javax.swing.JButton();
        bt_ultimo = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        tf_buscar = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jLabel8 = new javax.swing.JLabel();
        check_inicio = new javax.swing.JCheckBox();
        combo_proveedor = new javax.swing.JComboBox();

        setTitle("Registro de Productos");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("Registro de Productos");

        jLabel2.setText("Codigo.:");

        tf_codigo.setEditable(false);
        tf_codigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_codigoActionPerformed(evt);
            }
        });

        jLabel3.setText("Nombre.:");

        jLabel4.setText("Tipo.:");

        jLabel5.setText("Proveedor.:");

        tf_tipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_tipoActionPerformed(evt);
            }
        });

        tf_proveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_proveedorActionPerformed(evt);
            }
        });

        jLabel6.setText("Obs.:");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Codigo", "Nombre", "Tipo", "Proveedor", "Obs"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        bt_nuevo.setText("Nuevo");
        bt_nuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_nuevoActionPerformed(evt);
            }
        });

        bt_guardar.setText("Guardar");
        bt_guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_guardarActionPerformed(evt);
            }
        });

        bt_borrar.setText("Borrar");
        bt_borrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_borrarActionPerformed(evt);
            }
        });

        bt_primero.setText("|<");
        bt_primero.setToolTipText("Primero");
        bt_primero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_primeroActionPerformed(evt);
            }
        });

        bt_anterior.setText("<");
        bt_anterior.setToolTipText("Anterior");
        bt_anterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_anteriorActionPerformed(evt);
            }
        });

        bt_siguiente.setText(">");
        bt_siguiente.setToolTipText("Siguiente");
        bt_siguiente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_siguienteActionPerformed(evt);
            }
        });

        bt_ultimo.setText(">|");
        bt_ultimo.setToolTipText("Ultimo");
        bt_ultimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_ultimoActionPerformed(evt);
            }
        });

        jLabel7.setText("Buscar.:");

        tf_buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_buscarActionPerformed(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 204));

        grupo_orden.add(jRadioButton1);
        jRadioButton1.setText("Codigo");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        grupo_orden.add(jRadioButton2);
        jRadioButton2.setSelected(true);
        jRadioButton2.setText("Nombre");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });

        jLabel8.setText("Orden");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jRadioButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jRadioButton2))
                    .addComponent(jLabel8))
                .addContainerGap(23, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jRadioButton2)
                    .addComponent(jRadioButton1))
                .addContainerGap())
        );

        check_inicio.setSelected(true);
        check_inicio.setText("Comienza con");
        check_inicio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                check_inicioActionPerformed(evt);
            }
        });

        combo_proveedor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        combo_proveedor.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                combo_proveedorMouseClicked(evt);
            }
        });
        combo_proveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                combo_proveedorActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tf_descripcion))
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(tf_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tf_proveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(combo_proveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(18, 18, 18)
                                .addComponent(tf_obs, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(bt_nuevo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bt_guardar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bt_borrar)
                                .addGap(45, 45, 45)
                                .addComponent(bt_primero)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bt_anterior)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bt_siguiente)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bt_ultimo))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(108, 108, 108)
                                        .addComponent(jLabel1))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel7)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(check_inicio)
                                            .addComponent(tf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addGap(59, 59, 59)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(30, 30, 30)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(tf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(check_inicio)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(tf_descripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(tf_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tf_proveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(combo_proveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(tf_obs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_nuevo)
                    .addComponent(bt_guardar)
                    .addComponent(bt_borrar)
                    .addComponent(bt_primero)
                    .addComponent(bt_anterior)
                    .addComponent(bt_siguiente)
                    .addComponent(bt_ultimo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tf_codigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_codigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tf_codigoActionPerformed

    private void tf_proveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_proveedorActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tf_proveedorActionPerformed

    private void tf_tipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_tipoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tf_tipoActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        int linea = jTable1.getSelectedRow();
        posicion_actual = linea;
        tf_codigo.setText(jTable1.getValueAt(linea, 0).toString());
        tf_descripcion.setText(jTable1.getValueAt(linea, 1).toString());
        tf_tipo.setText(jTable1.getValueAt(linea, 2).toString());
        tf_proveedor.setText(jTable1.getValueAt(linea, 3).toString());
        tf_obs.setText(jTable1.getValueAt(linea, 4).toString());
        
    }//GEN-LAST:event_jTable1MouseClicked

    private void bt_nuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_nuevoActionPerformed
        tf_codigo.setText("");
        tf_descripcion.setText("");
        tf_tipo.setText("");
        tf_proveedor.setText("");
        tf_obs.setText("");
    }//GEN-LAST:event_bt_nuevoActionPerformed

    private void bt_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_guardarActionPerformed
        try
        {
            
            Session seccion = fabrica.openSession();
            Producto producto = new Producto();
             if(! tf_codigo.getText().equals(""))
                 producto.setCodigo(Integer.parseInt(tf_codigo.getText()));
            producto.setDescripcion(tf_descripcion.getText());
            producto.setTipo(Integer.parseInt(tf_tipo.getText()));
            producto.setProveedor(Integer.parseInt(tf_proveedor.getText()));
            producto.setObs(tf_obs.getText());
            Transaction tx_producto = seccion.beginTransaction();
            seccion.saveOrUpdate(producto);
            tx_producto.commit();
            seccion.clear();
            JOptionPane.showMessageDialog(null, "Registro guardado exitosamente....");
            rellenar_jtable();
        }
        catch(Exception erro)
        {
            JOptionPane.showMessageDialog(null,"Error en la insecion : "+erro );
        }
    }//GEN-LAST:event_bt_guardarActionPerformed

    private void bt_borrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_borrarActionPerformed
        String borrar = "Esta seguro que desea borrar el registro "+tf_descripcion.getText()+"?";
        int opcion_marcada = JOptionPane.showConfirmDialog(null,borrar, "Borrar",JOptionPane.YES_NO_CANCEL_OPTION);
        if (opcion_marcada == JOptionPane.YES_OPTION){
            try {
                
                Session seccion = fabrica.openSession();
                Producto producto = new Producto();
                posicion_actual = Integer.parseInt(tf_codigo.getText());
                producto.setCodigo(Integer.parseInt(tf_codigo.getText()));
                Transaction tx_producto = seccion.beginTransaction();
                seccion.delete(producto);
                tx_producto.commit();
                seccion.close();
                JOptionPane.showMessageDialog(null, "Se ha borrado con exito..");
                rellenar_jtable();
                
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Error al borrar "+e);
            }
        }else{
            JOptionPane.showMessageDialog(null, "No se borro el registro..");
        }
    }//GEN-LAST:event_bt_borrarActionPerformed

    private void bt_siguienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_siguienteActionPerformed
        if (posicion_actual < (tamano_lista-1)){
            posicion_actual ++;
            producto = lista_producto.get(posicion_actual);
            tf_codigo.setText(producto.getCodigo()+"");
            tf_descripcion.setText(producto.getDescripcion());
            tf_tipo.setText(producto.getTipo()+"");
            tf_proveedor.setText(producto.getProveedor()+"");
            tf_obs.setText(producto.getObs());
            jTable1.setRowSelectionInterval(posicion_actual, posicion_actual);
        }
        
        
    }//GEN-LAST:event_bt_siguienteActionPerformed

    private void bt_anteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_anteriorActionPerformed
        if (posicion_actual > 0 ){
            posicion_actual --;
            producto = lista_producto.get(posicion_actual);
            tf_codigo.setText(producto.getCodigo()+"");
            tf_descripcion.setText(producto.getDescripcion());
            tf_tipo.setText(producto.getTipo()+"");
            tf_proveedor.setText(producto.getProveedor()+"");
            tf_obs.setText(producto.getObs());
            jTable1.setRowSelectionInterval(posicion_actual, posicion_actual);
        }
    }//GEN-LAST:event_bt_anteriorActionPerformed

    private void bt_ultimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_ultimoActionPerformed

            producto = lista_producto.get(tamano_lista-1);
            tf_codigo.setText(producto.getCodigo()+"");
            tf_descripcion.setText(producto.getDescripcion());
            tf_tipo.setText(producto.getTipo()+"");
            tf_proveedor.setText(producto.getProveedor()+"");
            tf_obs.setText(producto.getObs());
            posicion_actual = tamano_lista-1;
            jTable1.setRowSelectionInterval(posicion_actual, posicion_actual);
    }//GEN-LAST:event_bt_ultimoActionPerformed

    private void bt_primeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_primeroActionPerformed
            producto = lista_producto.get(0);
            tf_codigo.setText(producto.getCodigo()+"");
            tf_descripcion.setText(producto.getDescripcion());
            tf_tipo.setText(producto.getTipo()+"");
            tf_proveedor.setText(producto.getProveedor()+"");
            tf_obs.setText(producto.getObs());
            posicion_actual = 0;
            jTable1.setRowSelectionInterval(posicion_actual, posicion_actual);
    }//GEN-LAST:event_bt_primeroActionPerformed

    private void tf_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_buscarActionPerformed
        if(check_inicio .isSelected())
            lista = "from Producto where upper(descripcion) like '"+tf_buscar.getText().toUpperCase()+"%'";
        else
            lista = "from Producto where upper(descripcion) like '%"+tf_buscar.getText().toUpperCase()+"%'";
        rellenar_jtable();
    }//GEN-LAST:event_tf_buscarActionPerformed

    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
        orden = " order by descripcion";
        rellenar_jtable();
    }//GEN-LAST:event_jRadioButton2ActionPerformed

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
        orden = " order by codigo";
        rellenar_jtable();
    }//GEN-LAST:event_jRadioButton1ActionPerformed

    private void check_inicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_check_inicioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_check_inicioActionPerformed

    private void combo_proveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo_proveedorActionPerformed
        JOptionPane.showMessageDialog(null, "El item seleccionado es : "+combo_proveedor.getSelectedItem());
        tf_proveedor.setText(buscarProveedor()+"");
    }//GEN-LAST:event_combo_proveedorActionPerformed

    private void combo_proveedorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_combo_proveedorMouseClicked
        JOptionPane.showMessageDialog(null, "El item seleccionado es : "+combo_proveedor.getSelectedItem());
    }//GEN-LAST:event_combo_proveedorMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(formProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(formProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(formProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(formProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new formProducto().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_anterior;
    private javax.swing.JButton bt_borrar;
    private javax.swing.JButton bt_guardar;
    private javax.swing.JButton bt_nuevo;
    private javax.swing.JButton bt_primero;
    private javax.swing.JButton bt_siguiente;
    private javax.swing.JButton bt_ultimo;
    private javax.swing.JCheckBox check_inicio;
    private javax.swing.JComboBox combo_proveedor;
    private javax.swing.ButtonGroup grupo_orden;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField tf_buscar;
    private javax.swing.JTextField tf_codigo;
    private javax.swing.JTextField tf_descripcion;
    private javax.swing.JTextField tf_obs;
    private javax.swing.JTextField tf_proveedor;
    private javax.swing.JTextField tf_tipo;
    // End of variables declaration//GEN-END:variables
    
    
    public void rellenar_jtable(){
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(200);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(200);
        
        DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel();
        modelo.setNumRows(0);
        
        try{
            Session session = fabrica.openSession();
            lista_producto = session.createQuery(lista+orden).list();
            tamano_lista = lista_producto.size();
            String datos = "";
            for(int i=0; i<tamano_lista; i++){
                producto = lista_producto.get(i);
                modelo.addRow(new Object[] {producto.getCodigo(),
                                            producto.getDescripcion(),
                                            producto.getTipo(),
                                            producto.getProveedor(),
                                            producto.getObs()});
            }
            if (!lista_producto.isEmpty()){
                posicion_actual = 0;
                producto = lista_producto.get(0);
                tf_codigo.setText(producto.getCodigo()+"");
                tf_descripcion.setText(producto.getDescripcion());
                tf_tipo.setText(producto.getTipo()+"");
                tf_proveedor.setText(producto.getProveedor()+"");
                tf_obs.setText(producto.getObs());
                jTable1.setRowSelectionInterval(0, 0);
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "Error al listar en el JTable "+e);
        }
    }
    
    public void rellenaJComboBox(){
        Session seccion = fabrica.openSession();
        try {
            Criteria crit = seccion.createCriteria(Proveedor.class);
            List<Proveedor> resulset = crit.list();
            combo_proveedor.removeAllItems();
            for (Proveedor prov : resulset) {
                combo_proveedor.addItem(""+prov.getDescripcion());
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Ocurrio un error al cargar el jcombobox proveedor "+e);
        }
    }
    
    public String buscarProveedor(){
        String pbuscar = null;
        try {
            Session session = fabrica.openSession();
//            String sql = "from Proveedor where descripcion like '%"+combo_proveedor.getSelectedItem()+"%'";
            String sql = "from Proveedor where descripcion = "+combo_proveedor.getSelectedItem();
            pbuscar = session.createQuery(sql).toString();
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Ocurrio un error en buscar proveedor "+e);
        }
        return pbuscar;
    }
    
}

